package com.iwhalecloud.citybrain.flow.platform.manager.application.service.impl.task;

import java.util.Objects;

import com.iwhalecloud.citybrain.flow.platform.manager.application.listener.MultiInstanceSingleCompleteListener;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.monitor.FlowTaskTraceVo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.FlowTaskTraceRepository;
import com.iwhalecloud.citybrain.flow.platform.manager.application.utils.SpringUtils;
import org.flowable.engine.delegate.TaskListener;
import org.flowable.task.service.delegate.DelegateTask;

/**
 * MultiInstanceTaskCompleteListener - 会签任务完成后统计通过与不通过的数量
 *
 * @author lilh
 * @date 2019-03-06 10:23
 */
public class MultiInstanceTaskCompleteListener extends MultiInstanceSingleCompleteListener implements TaskListener {

    @Override
    public void notify(DelegateTask delegateTask) {
        //1.获取当前任务的办理状态，通过或者不通过
        String approval = (String) delegateTask.getVariableLocal(APPROVAL);
        if(null!=approval){
            approval=approval.toLowerCase();
        }
        this.updateStatistic(delegateTask, Objects.equals(PASS, approval) ? NUMBER_OF_PASS_INSTANCES : NUMBER_OF_UNPASS_INSTANCES, approval);
    }

    private void updateStatistic(DelegateTask delegateTask, String variableName, String approval) {
        Integer number = (Integer) delegateTask.getVariable(variableName);
        if (Objects.isNull(number)) {
            number = 0;
        }
        delegateTask.setVariable(variableName, number + 1);
        updateMultiInstanceTaskTrace(approval, number + 1, delegateTask);
    }

    private void updateMultiInstanceTaskTrace(String approval, int newCount, DelegateTask delegateTask) {
        FlowTaskTraceVo taskTrace = resolveTaskTrace(delegateTask);
        if (Objects.isNull(taskTrace)) {
            return;
        }
        updateMultiInstanceTaskTrace(approval, newCount, taskTrace.getParentId());
    }

    private FlowTaskTraceVo resolveTaskTrace(DelegateTask delegateTask) {
        FlowTaskTraceRepository taskTraceService = SpringUtils.getBean(FlowTaskTraceRepository.class);
        return taskTraceService.getTaskTraceByTaskId(delegateTask.getId());
    }
}
